import 'package:citiesocial/_include.dart';

class GoodsByHot extends BaseStatefulWidget {
  GoodsByHot();
  @override
  State<StatefulWidget> createState() => _GoodsByHotState();
}

class _GoodsByHotState extends BaseState<GoodsByHot> {
  final _gridMargin = 10.0;
  final _list = List<GoodsEntity>();
  var _page = 1;
  var _loadable = true;
  _GoodsByHotState();

  void _loadData() async {
    LoadingDialog.show(context);
    final goodsList =
        await HttpManager.getHotGoods(context: context, page: _page);

    if (_page == 1) {
      _list.clear();
    }
    if (goodsList != null && goodsList.length > 0) {
      _loadable = goodsList.length >= HttpManager.default_size;
      _list.addAll(goodsList);
    } else {
      _loadable = false;
    }
    LoadingDialog.dismiss(context);
    setState(() {});
  }

  @override
  void initState() {
    Future.delayed(Configs.loadDelay, () {
      _loadData();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBarUtils.withCart(context, title: '热门商品'),
        backgroundColor: Colors.white,
        body: SafeArea(
          child: DScrollView(
            onRefresh: () async {
              _loadable = true;
              _page = 1;
              _loadData();
            },
            onLoadmore: () {
              if (_loadable) {
                _page++;
                _loadData();
              }
            },
            child: Container(
              child: Wrap(
                children:
                    List.generate(_list == null ? 0 : _list.length, (index) {
                  return SquareGoodsItem(
                    _list[index],
                    width:
                        (MediaQuery.of(context).size.width - _gridMargin * 4) /
                            2,
                    margin: EdgeInsets.symmetric(horizontal: _gridMargin / 2),
                  );
                }),
              ),
              margin: EdgeInsets.symmetric(horizontal: _gridMargin),
            ),
          ),
        ),
      );
}
